<?php
/**
 * TomatoCMS
 *
 * LICENSE
 *
 * This source file is subject to the GNU GENERAL PUBLIC LICENSE Version 2
 * that is bundled with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://www.gnu.org/licenses/gpl-2.0.txt
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@tomatocms.com so we can send you a copy immediately.
 *
 * @copyright    Copyright (c) 2009-2010 TIG Corporation (http://www.tig.vn)
 * @license        http://www.gnu.org/licenses/gpl-2.0.txt GNU GENERAL PUBLIC LICENSE Version 2
 * @version     $Id: AttributeController.php 3075 2010-05-26 15:41:59Z huuphuoc $
 */

class Shop_AttributeController extends Zend_Controller_Action
{
    /* ========== Backend actions =========================================== */

    /**
    * List attributes
    *
    * @return void
    */
    public function listAction()
    {
        $request = $this->getRequest();
        /**
        * Get connection to database
        **/
        $conn = Tomato_Db_Connection::factory()->getMasterConnection();

        /**
         * Attribute access model access to database
         **/
        $attributeDao = Tomato_Model_Dao_Factory::getInstance()->setModule('shop')->getAttributeDao();
        $attributeDao->setDbConnection($conn);

        /**
         * Category model access to database
         **/
        $categoryDao = Tomato_Model_Dao_Factory::getInstance()->setModule('shop')->getCategoryDao();
        $categoryDao->setDbConnection($conn);

        /**
         * Get category to show select box
         **/
        $categories = $categoryDao->getCategoryTree();
        $this->view->assign('categories', $categories);

        $pageIndex = $request->getParam('pageIndex', 1);
        $perPage   = 20;
        $offset    = ($pageIndex - 1) * $perPage;
        $purifier     = new HTMLPurifier();
        $exp = null;

        /**
         * Get param when to search
         **/
        if ($request->isPost()) {
            $attribute_type_admin_name = $request->getPost('attribute_type_admin_name');
            $category_id = $request->getPost('category_id');

            if($attribute_type_admin_name){
                $exp['attribute_type_admin_name'] = $purifier->purify($attribute_type_admin_name);
            }
            if($category_id){
                $exp['category_id'] = $purifier->purify($category_id);
            }
            $params = rawurlencode(base64_encode(Zend_Json::encode($exp)));
        } else {
            $params = $request->getParam('q');
            if ($params != null) {
                $exp = rawurldecode(base64_decode($params));
                $exp = Zend_Json::decode($exp);
            } else {
                $params = rawurlencode(base64_encode(Zend_Json::encode($exp)));
            }
        }

        $attributes = $attributeDao->find($offset, $perPage, $exp);
        $total      = $attributeDao->count($exp);

        /**
        * Get all category name for each attribute
        * Get attribute content each language
        **/
        $arrCategory = array();
        $arrAttributeType = array();
        if ($total > 0){
            foreach($attributes as $attribute){
                $strCategory = substr(substr($attribute->category_id,1),0,-1);
                $arrCategoryId = explode(',',$strCategory); $count = count($arrCategoryId);
                if($arrCategoryId){
                    $strCategoryName = null;
                    foreach($arrCategoryId as $category_id){
                        $category = $categoryDao->getCategoryById($category_id);
                        $strCategoryName .= $category->category_admin_name.', ';
                    }
                    $arrCategory[$attribute->attribute_type_id] = substr(substr($strCategoryName,0),0,-2);
                }
            }
            /**Get attribute language content*/
            foreach($attributes as $row)
            {
                $attributeContentById = $attributeDao->getAttributeContentById($row->attribute_type_id);
                $strContent = null;
                foreach($attributeContentById as $rowAttributeContentById)
                {
                    $strContent .= $rowAttributeContentById->attribute_type_content_name.'<br>';
                    $arrAttributeType[$row->attribute_type_id] = substr(substr($strContent,0),0,-4);
                }
            }
        }
        $this->view->assign('arrCategory', $arrCategory);
        $this->view->assign('arrAttributeType', $arrAttributeType);

        /**
        * Paginator
        */
        $paginator = new Zend_Paginator(new Tomato_Utility_PaginatorAdapter($attributes, $total));
        $paginator->setCurrentPageNumber($pageIndex);
        $paginator->setItemCountPerPage($perPage);

        $this->view->assign('exp', $exp);
        $this->view->assign('pageIndex', $pageIndex);
        $this->view->assign('attributes', $attributes);
        $this->view->assign('numAttribute', $total);

        $this->view->assign('paginator', $paginator);
        $this->view->assign('paginatorOptions', array(
            'path'        => $this->view->url(array(), 'attribute_attribute_list'),
            'itemLink' => (null == $params)
                            ? 'page-%d'
                            : 'page-%d/' . '?q=' . $params,
        ));
    }

    /**
     * Create new attribute
     * @return void
     **/
    public function addAction()
    {
        $request = $this->getRequest();

        /**
        * Get connection to database
        **/
        $conn = Tomato_Db_Connection::factory()->getMasterConnection();

        /**
         * Attribute access model access to database
         **/
        $attributeDao = Tomato_Model_Dao_Factory::getInstance()->setModule('shop')->getAttributeDao();
        $attributeDao->setDbConnection($conn);

        /**
         * Category model access to database
         **/
        $categoryDao = Tomato_Model_Dao_Factory::getInstance()->setModule('shop')->getCategoryDao();
        $categoryDao->setDbConnection($conn);

        /**
         * Get category to show select box
         **/
        $categories = $categoryDao->getCategoryTree();
        $this->view->assign('categories', $categories);

        if ($request->isPost()){
            $attribute_type_admin_name = $request->getPost('attribute_type_admin_name');
            $category_id = $request->getPost('category_id');
            $strId = implode(',', $category_id);
            $attributes = new Shop_Models_Attribute(array(
                    'attribute_type_admin_name' => $attribute_type_admin_name,
                    'category_id'               => ','.$strId.',',
            ));
            $id = $attributeDao->add($attributes);
            if ($id) {
                $this->_helper->getHelper('FlashMessenger')->addMessage(
                    $this->view->translator('attribute_add_success')
                );
                $this->_redirect($this->view->serverUrl().$this->view->url(array('attribute_id' => $id), 'attribute_attribute_edit'));
            }
        }
    }

    /**
    * Update attribute
    *
    * @return void
    */
    public function editAction()
    {
        $request = $this->getRequest();

        $id = $request->getParam('attribute_id');
        $this->view->assign('id', $id);

        /**
        * Get connection to database
        **/
        $conn = Tomato_Db_Connection::factory()->getMasterConnection();

        /**
         * Attribute access model access to database
         **/
        $attributeDao = Tomato_Model_Dao_Factory::getInstance()->setModule('shop')->getAttributeDao();
        $attributeDao->setDbConnection($conn);

        /**
         * Category model access to database
         **/
        $categoryDao = Tomato_Model_Dao_Factory::getInstance()->setModule('shop')->getCategoryDao();
        $categoryDao->setDbConnection($conn);

        /**
         * Get category to show select box
         **/
        $categories = $categoryDao->getCategoryTree();
        $this->view->assign('categories', $categories);

        /**
         * Get all language system
         **/
        $lanuguages = $categoryDao->getLanguage();
        $this->view->assign('languages', $lanuguages);

        /**
        * Get attribute content
        **/
        $attributeContent = $attributeDao->getAttributeContentById($id);
        $arrAttributeContent = array();
        if(count($attributeContent) > 0){
            foreach ($attributeContent as $row){
                $arrAttributeContent[$row->language_code] = $row;
            }
        }
        $this->view->assign('arrAttributeContent', $arrAttributeContent);

        /**
        * Get attribute basic info
        **/
        $attribute = $attributeDao->getAttributeById($id);
        $this->view->assign('attribute', $attribute);
        if ($request->isPost())
        {
            $attribute_type_admin_name = $request->getPost('attribute_type_admin_name');
            $category_id = $request->getPost('category_id');
            $strId = implode(',', $category_id);
            $attributes = new Shop_Models_Attribute(array(
                    'attribute_type_id'         => $id,
                    'attribute_type_admin_name' => $attribute_type_admin_name,
                    'category_id'               => ','.$strId.',',
            ));
            $attributeDao->update($attributes);
            $this->_helper->getHelper('FlashMessenger')->addMessage(
                    $this->view->translator('attribute_edit_success')
            );
            $this->_redirect($this->view->serverUrl().$this->view->url(array('attribute_id' => $id), 'attribute_attribute_edit'));
        }
    }

    /**
    * Save content information of attribute follow language
    * @return void
    **/
    public function saveContentAction(){
        $this->_helper->getHelper('layout')->disableLayout();
        $this->_helper->getHelper('viewRenderer')->setNoRender();

        $request = $this->getRequest();
        if($request->isPost()){
            $id = $request->getParam('attribute_id');

            /**
            * Get connection to database
            **/
            $conn = Tomato_Db_Connection::factory()->getMasterConnection();

            /**
            * Attribute access model access to database
            **/
            $attributeDao = Tomato_Model_Dao_Factory::getInstance()->setModule('shop')->getAttributeDao();
            $attributeDao->setDbConnection($conn);

            $attribute_type_content_id          = $request->getPost('attribute_type_content_id');
            $language_code                      = $request->getPost('language_code');
            $attribute_type_content_name        = $request->getPost('attribute_type_content_name');
            $attribute_type_content_description = $request->getPost('attribute_type_content_description');

            $attribute = new Shop_Models_Attribute(array(
                'attribute_type_content_name'           => $attribute_type_content_name,
                'attribute_type_content_description'    => $attribute_type_content_description,
                'attribute_type_id'                     => $id,
                'language_code'                         => $language_code,
            ));
            if($attribute_type_content_id){
                $attribute->attribute_type_content_id = $attribute_type_content_id;
                $attributeDao->updateContent($attribute);
            }else{
                $attributeDao->addContent($attribute);
            }
            $this->_helper->getHelper('FlashMessenger')->addMessage(
                $this->view->translator('attribute_save_content_success')
            );
            $this->_redirect($this->view->serverUrl().$this->view->url(array('attribute_id' => $id), 'attribute_attribute_edit'));
        }
    }

    public function deleteAction(){
        $this->_helper->getHelper('layout')->disableLayout();
        $this->_helper->getHelper('viewRenderer')->setNoRender();

        $response = 'RESULT_ERROR';
        $request  = $this->getRequest();
        if ($request->isPost()) {
            $id = $request->getPost('id');
            /**
             * Get connection to database
             **/
            $conn = Tomato_Db_Connection::factory()->getMasterConnection();

            /**
             * Attribute models access to data
             **/
            $attributeDao = Tomato_Model_Dao_Factory::getInstance()->setModule('shop')->getAttributeDao();
            $attributeDao->setDbConnection($conn);

            /**
             * Check attribute is used
             **/
            $countAtt = $attributeDao->countAttribute($id);

            $pd_used = ($countAtt > 0)?true:false;

            /**
             * delete attribute
             **/
            if(!$pd_used){
                $attributeDao->delete($id);
                $response = 'RESULT_OK';
            }else{
                $response = 'RESULT_IS_USED';
            }
        }
        $this->getResponse()->setBody($response);
    }

    /**
     * Add  value for attribute of products
     * @return void
     **/
    public function valueAction()
    {
        $request = $this->getRequest();

        $product_id = $request->getParam('product_id');
        $att_id = $request->getParam('att');

        $this->view->assign('product_id', $product_id);
        $this->view->assign('att_id', $att_id);

        /**
        * Get link to upload image
        **/
        $this->view->addHelperPath(TOMATO_APP_DIR . DS . 'modules' . DS . 'upload' . DS . 'views' . DS . 'helpers', 'Upload_View_Helper_');

        /**
        * Get connection to database
        **/
        $conn = Tomato_Db_Connection::factory()->getMasterConnection();

        /**
         * Attribute model access to database;
         **/
        $attributeDao = Tomato_Model_Dao_Factory::getInstance()->setModule('shop')->getAttributeDao();
        $attributeDao->setDbConnection($conn);

        /**
         * Value model access to database;
         **/
        $valueDao = Tomato_Model_Dao_Factory::getInstance()->setModule('shop')->getValueDao();
        $valueDao->setDbConnection($conn);

        /**
         * Category model access to database
         **/
        $categoryDao = Tomato_Model_Dao_Factory::getInstance()->setModule('shop')->getCategoryDao();
        $categoryDao->setDbConnection($conn);

        /**
         * Get all language system
         **/
        $languages = $categoryDao->getLanguage();
        $this->view->assign('languages', $languages);

        /**
         * Get attribute for product
         **/
        $attributeTypeByProductId = $attributeDao->getAttributeTypeByProductId($product_id);
        $this->view->assign('attributes', $attributeTypeByProductId);

        if($request->isPost()){

            $number_box = $request->getPost('number_box');
            $attribute_type_id = $request->getPost('attribute_type_id');

            $saveValueTypeId = ',';/**string all id had been updated to add table shop_product_attribute*/

            for($i=1;$i<=$number_box;$i++){
                $value_type_name  = $request->getPost('value_type_name_'.$i);
                $value_type_icon  = $request->getPost('value_type_icon_'.$i);
                $tags             = $request->getPost('tags_'.$i);
                $value_type_costs = $request->getPost('value_type_costs_'.$i);
                $value_type_price = $request->getPost('value_type_price_'.$i);

                $value_type_id = $request->getPost('value_type_id_'.$i);
                $cb_del_value = $request->getPost('cb_del_value_'.$value_type_id);

                $value_type = new Shop_Models_Value(array(
                    'value_type_name'   => $value_type_name,
                    'value_type_icon'   => $value_type_icon,
                    'tags'              => $tags,
                    'value_type_costs'  => $value_type_costs,
                    'value_type_price'  => $value_type_price,
                ));
                if(!$value_type_id){
                    if(trim($value_type_name)){
                        $id = $valueDao->add($value_type);
                    }
                    else{
                        $id = null;
                    }
                }else{
                    $id = $value_type_id;
                    $value_type->value_type_id = $value_type_id;
                    if(trim($value_type_name)){
                        $valueDao->update($value_type);
                    }else{
                        $id = null;
                    }
                }

                /**
                 * Check delete value
                **/
                $countValue = $valueDao->countValue($id);
                $countValue1 = $valueDao->countValue1($id);
                $countVal = $countValue+$countValue1;

                if(!$cb_del_value && $countVal <= 0){
                    if(null != $id){
                        $saveValueTypeId .= $id.',';
                    }
                }else{
                    if($countVal <= 0){
                        if($valueDao->deleteValue($id));{
                            $valueDao->deleteValueContent($id);
                        }
                    }else{
                        $saveValueTypeId .= $id.',';
                    }
                }

                /**
                 * Save content language for value
                 **/
                if($id){
                    foreach($languages as $language){
                        $value_type_id                 = $id;
                        $language_code                 = $request->getPost('language_code_'.$i.'_'.$language->language_code);
                        $value_content_id                 = $request->getPost('value_content_id_'.$i.'_'.$language->language_code);
                        $value_content_name         = $request->getPost('value_content_name_'.$i.'_'.$language->language_code);
                        $value_content_description    = $request->getPost('value_content_description_'.$i.'_'.$language->language_code);

                        $value_content = new Shop_Models_Value(array(
                            'value_type_id'               => $value_type_id,
                            'value_content_name'           => $value_content_name,
                            'value_content_description'    => $value_content_description,
                            'language_code'             => $language_code,
                        ));
                        if(!$value_content_id){
                            if(trim($value_content_name)){
                                $idContent = $valueDao->addContent($value_content);
                            }
                        }else{
                            $value_content->value_content_id = $value_content_id;
                            if(trim($value_content_name)){
                                $valueDao->updateContent($value_content);
                            }
                        }
                    }
                }
            }

            /**
             * Save value type chain for relationship product and attribute
            **/
            $attributeDao->updateValueTypeIdChainByAttributeTypeId($attribute_type_id,$saveValueTypeId,$product_id);

            $this->_helper->getHelper('FlashMessenger')->addMessage(
                $this->view->translator('value_save_success')
            );
            $this->_redirect($this->view->serverUrl().$this->view->url(array('product_id' => $product_id), 'shop_product_attribute_value').'/?att='.$attribute_type_id);
        }
    }

    /**
     * Get box value html to add
     * @return: html
     **/
    public function ajaxBoxAction(){
        $this->_helper->getHelper('layout')->disableLayout();

        /**
        * Get link to upload image
        **/
        $this->view->addHelperPath(TOMATO_APP_DIR . DS . 'modules' . DS . 'upload' . DS . 'views' . DS . 'helpers', 'Upload_View_Helper_');

        $request = $this->getRequest();

        $number = $request->getParam('number');
        $index = $request->getParam('index');

        /**
        * Get connection to database
        **/
        $conn = Tomato_Db_Connection::factory()->getMasterConnection();

        /**
         * Category model access to database
         **/
        $categoryDao = Tomato_Model_Dao_Factory::getInstance()->setModule('shop')->getCategoryDao();
        $categoryDao->setDbConnection($conn);

        /**
         * Get all language system
         **/
        $lanuguages = $categoryDao->getLanguage();
        $this->view->assign('languages', $lanuguages);

        $this->view->assign('number', $number);
        $this->view->assign('index', $index);
    }

    public function ajaxValueAction(){
        $this->_helper->getHelper('layout')->disableLayout();

        /**
        * Get link to upload image
        **/
        $this->view->addHelperPath(TOMATO_APP_DIR . DS . 'modules' . DS . 'upload' . DS . 'views' . DS . 'helpers', 'Upload_View_Helper_');

        $request = $this->getRequest();

        /**
        * Get connection to database
        **/
        $conn = Tomato_Db_Connection::factory()->getMasterConnection();

        /**
         * Category model access to database
         **/
        $categoryDao = Tomato_Model_Dao_Factory::getInstance()->setModule('shop')->getCategoryDao();
        $categoryDao->setDbConnection($conn);

        /**
         * Get all language system
         **/
        $lanuguages = $categoryDao->getLanguage();
        $this->view->assign('languages', $lanuguages);

        /**
         * Attribute model access to database;
         **/
        $attributeDao = Tomato_Model_Dao_Factory::getInstance()->setModule('shop')->getAttributeDao();
        $attributeDao->setDbConnection($conn);

        /**
         * Value model access to database;
         **/
        $valueDao = Tomato_Model_Dao_Factory::getInstance()->setModule('shop')->getValueDao();
        $valueDao->setDbConnection($conn);

        /**
        * Assign value default for variable
        **/
        $number = 0;
        $arrValue = array();
        $arrValueContent = array();

        if($request->isPost()){
            $attribute_type_id     = $request->getPost('id');
            $product_id         = $request->getPost('pId');

            /**
            * Get all value type id fo producd and attribute
            **/
            $valueChain = $attributeDao->getValueTypeIdChainByAttributeTypeId($attribute_type_id,$product_id);
            $arrValueChain = isset($valueChain->value_type_id_chain)?explode(',',substr(substr($valueChain->value_type_id_chain,1),0,-1)):null;

            /**
            * Get number value type id
            **/
            $number = (null==$arrValueChain[0])?0:count($arrValueChain);
            if($number>0){
                foreach($arrValueChain as $id){
                    /**
                    * Get basic value information
                    **/
                    $value = $valueDao->getById($id);
                    $arrValue[] = $value;

                    /**
                     * Get language content value information
                    **/
                    $valueContent = $valueDao->getValueContentById($id);
                    if(count($valueContent)>0){
                        $arrContent = array();
                        foreach($valueContent as $content){
                            $arrContent[$content->language_code] = $content;
                        }
                        $arrValueContent[$id] = $arrContent;
                    }
                }
            }
        }

        $this->view->assign('arrValue', $arrValue);
        $this->view->assign('arrValueContent', $arrValueContent);
        $this->view->assign('number', $number);
        $this->view->assign('a_id', $attribute_type_id);
        $this->view->assign('p_id', $product_id);
    }

    /**
    * Not use this action
    **/
    public function deleteValueAction(){
        $this->_helper->getHelper('layout')->disableLayout();
        $this->_helper->getHelper('viewRenderer')->setNoRender();

        $request = $this->getRequest();

        /**
        * Get connection to database
        **/
        $conn = Tomato_Db_Connection::factory()->getMasterConnection();

        /**
         * Value model access to database;
         **/
        $valueDao = Tomato_Model_Dao_Factory::getInstance()->setModule('shop')->getValueDao();
        $valueDao->setDbConnection($conn);

        $result  = 'RESULT_ERROR';
        if ($request->isPost()) {
            $product_id = $request->getPost('p_id');
            $attribute_type_id = $request->getPost('a_id');
            $value_type_id = $request->getPost('value');

            $conditions = array(
                'product_id' => $product_id,
                'attribute_type_id' => $attribute_type_id,
                'value_type_id' => $value_type_id,
            );
            $valueDao->delete($conditions);
            $result = 'RESULT_OK';
        }
        $this->getResponse()->setBody($result);
    }
}
